<script lang="ts">
export default {
    name: 'FilesUpload'
};
</script>

<script setup lang="ts">
import { ref, withDefaults, defineEmits, computed } from 'vue';
import { Plus, Download, Delete } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { uploadFile as uploadRequest } from '@/api/common';
import fileIcon from '@/assets/images/file.png';

import type {
    UploadProps,
    UploadUserFile,
    UploadRawFile,
    UploadFile,
    UploadFiles,
    UploadRequestOptions,
    UploadProgressEvent
} from 'element-plus';

const props = withDefaults(
    defineProps<{
        fileList: { id: number; name: string }[];
        remark: string;
        // type: number; // 文件类型：1-图片 2-视频 3-音频 4-Word文档 5-PDF 99-其他
        limit?: number;
        disabled?: boolean;
    }>(),
    {
        fileList: () => [],
        remark: '文件',
        limit: 9,
        disabled: true
    }
);

// const fileList = ref<UploadUserFile[]>([
//     {
//         name: 'food.jpeg',
//         url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
//     }
// ]);

const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const action = import.meta.env.VITE_APP_BASE_API + '/admin/api/file/upload';
const downLoadFile = (id: number) => {
    console.log(id);
    window.open(
        import.meta.env.VITE_APP_BASE_API + `/admin/api/file/download/${id}`
    );
};
const fileList = computed(() => {
    return props.fileList.map((item, index) => {
        return {
            name: item?.name,
            index,
            url: `${import.meta.env.VITE_PIC_HOST}/admin/api/file/show/image/${item?.id}`,
            id: item?.id as number
        };
    });
});

// ['remove', 'beforeUpload', 'success']
const emits = defineEmits<{
    (
        e: 'remove',
        data: {
            uploadFile: UploadFile;
            index: number;
            uploadFiles?: UploadFiles;
        }
    ): void;
    (e: 'beforeUpload', data: UploadRawFile): void;
    (e: 'success', data: { id: number; name: string }[]): void;
    (e: 'isUpload', value: boolean): void;
}>();

const handleUpload = (rawFile: UploadRawFile) => {
    emits('beforeUpload', rawFile);
};

/**
 * 删除
 * @param uploadFile
 * @param uploadFiles
 */
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    emits('remove', {
        uploadFile,
        index: (uploadFile as any).index,
        uploadFiles
    });
};

/**
 *
 * @param uploadFile 预览
 */
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    // dialogImageUrl.value = uploadFile.url || '';
    // dialogVisible.value = true;
};

const handleSuccess = (
    response: any,
    uploadFile: UploadFile,
    uploadFiles: UploadFiles
) => {
    if (uploadFiles.every((it) => it.status == 'success')) {
        emits(
            'success',
            uploadFiles
                .filter((item) => item.response)
                .map((item) => {
                    return {
                        id: (item.response as any).data as number,
                        name: item.name
                    };
                })
        );
    }
};

const handleExceed = () => {
    ElMessage({
        type: 'error',
        message: `最多上传${props.limit}个文件`
    });
};

const handleRequest = (options: UploadRequestOptions) => {
    const rawFile = options.file;
    const arr = rawFile.name.split('.');
    const suffix = arr[arr.length - 1] || '';
    let type = 99;
    if (
        rawFile.type.indexOf('jpeg') !== -1 ||
        rawFile.type.indexOf('png') !== -1 ||
        rawFile.type.indexOf('heic') !== -1
    ) {
        type = 1;
    } else if (rawFile.type.indexOf('video') !== -1) {
        type = 2;
    } else if (['m4a', 'mp3'].includes(suffix)) {
        type = 3;
    } else if (['doc', 'docx'].includes(suffix)) {
        type = 4;
    } else if (['pdf'].includes(suffix)) {
        type = 5;
    } else {
        type = 99;
    }

    emits('isUpload', true);
    // console.log("111111111",rawFile.type, rawFile.name, type, suffix);
    return uploadRequest({
        remark: options.data.remark as string,
        file: options.file,
        type
    });
};
const isDisable = () => {
    if (!props.disabled) {
        return 'ul-list';
        // return 'margin-top: -40px;'
    }
};

let showProcess = ref(false);
let progress = ref(0);
// 上传文件
const changeFile = (file: any, fileLists: any) => {
    // 文件上传进度条
    if (file.status === 'ready') {
        progress.value = 0;
        showProcess.value = true;
        const interval = setInterval(() => {
            if (progress.value >= 99) {
                clearInterval(interval);
                return;
            }
            progress.value += 1;
        }, 20);
    }
    if (file.status == 'success') {
        progress.value = 100;
        showProcess.value = false;
        emits('isUpload', false);
    }
};
</script>

<template>
    <div class="filesupload-container">
        <el-upload
            :file-list="fileList"
            :limit="props.limit"
            :action="action"
            :data="{
                remark: props.remark
            }"
            :before-upload="handleUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :http-request="handleRequest"
            multiple
            :on-success="handleSuccess"
            :disabled="!props.disabled"
            :class="isDisable()"
            :on-change="changeFile"
        >
            <!-- <el-icon><Plus /></el-icon> -->
            <template #default v-if="props.disabled">
                <el-button type="primary" :disabled="!props.disabled"
                    >上传文件</el-button
                >
            </template>
            <template #file="{ file }">
                <div class="file_list" style="width: 100%">
                    <img :src="fileIcon" width="20" height="20" class="mr10" />
                    <div class="mr10">{{ file.name }}</div>
                    <div>
                        <el-button
                            style="
                                color: #4b9df5;
                                background-color: transparent;
                                border: none;
                            "
                            text
                            :icon="Download"
                            @click="() => downLoadFile(file.id)"
                            >下载</el-button
                        >
                        <el-button
                            style="background-color: transparent; border: none"
                            v-if="props.disabled"
                            type="danger"
                            :icon="Delete"
                            text
                            @click="
                                () =>
                                    emits('remove', {
                                        uploadFile: file,
                                        index: file.index
                                    })
                            "
                            >删除</el-button
                        >
                    </div>
                </div>
            </template>
        </el-upload>

        <el-progress v-if="showProcess" :percentage="progress" />

        <el-dialog v-model="dialogVisible">
            <div>
                <img
                    style="width: 100%"
                    :src="dialogImageUrl"
                    alt="Preview Image"
                />
            </div>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.filesupload-container {
    width: 100%;
}

.ul-list {
    :deep(.el-upload-list) {
        margin-top: -25px !important;
    }
}

.file_list {
    display: inline-flex;
    flex-direction: row;
    align-items: center;
}
</style>
